// add-card.js - 处理添加名片的功能

document.addEventListener('DOMContentLoaded', async () => {
  // 从localStorage获取当前用户和JWT令牌
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  const token = localStorage.getItem('token');
  
  if (!currentUser || !token) {
    // 如果没有用户信息或令牌，重定向到登录页面
    window.location.href = 'login.html';
    return;
  }
  
  // 加载名片夹数据
  await loadFolders();
  
  // 添加表单提交事件
  document.getElementById('cardForm').addEventListener('submit', handleFormSubmit);
});

/**
 * 加载名片夹数据到下拉选择框
 */
async function loadFolders() {
  try {
    showLoading();
    
    // 检查JWT令牌是否存在
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('认证失败：未找到令牌');
    }
    
    // 获取名片夹列表 - API会自动添加令牌到请求头
    const response = await window.api.folders.getAll();
    
    if (!response.success) {
      throw new Error('获取名片夹数据失败: ' + (response.message || ''));
    }
    
    const folderSelect = document.getElementById('folder');
    // 清空现有选项（除了默认提示选项）
    folderSelect.innerHTML = '';
    
    // 添加提示选项
    const defaultOption = document.createElement('option');
    defaultOption.value = '';
    defaultOption.textContent = '请选择名片夹';
    defaultOption.selected = true;
    defaultOption.disabled = true;
    folderSelect.appendChild(defaultOption);
    
    // 添加名片夹选项
    if (response.folders && response.folders.length > 0) {
      response.folders.forEach(folder => {
        const option = document.createElement('option');
        option.value = folder.id;
        option.textContent = folder.name;
        folderSelect.appendChild(option);
      });
    } else {
      // 如果没有名片夹，显示创建提示
      folderSelect.innerHTML = '';
      const noFoldersOption = document.createElement('option');
      noFoldersOption.value = '';
      noFoldersOption.textContent = '请先创建名片夹';
      noFoldersOption.disabled = true;
      noFoldersOption.selected = true;
      folderSelect.appendChild(noFoldersOption);
      
      // 显示提示信息
      const formContainer = document.querySelector('.container');
      const alertDiv = document.createElement('div');
      alertDiv.style.color = '#721c24';
      alertDiv.style.backgroundColor = '#f8d7da';
      alertDiv.style.padding = '10px';
      alertDiv.style.marginBottom = '15px';
      alertDiv.style.borderRadius = '4px';
      alertDiv.textContent = '您尚未创建任何名片夹。请先创建名片夹后再添加名片。';
      
      const createButton = document.createElement('button');
      createButton.textContent = '创建名片夹';
      createButton.style.marginLeft = '10px';
      createButton.style.backgroundColor = '#28a745';
      createButton.onclick = () => {
        window.location.href = 'folder-management.html';
      };
      
      alertDiv.appendChild(createButton);
      formContainer.insertBefore(alertDiv, document.getElementById('cardForm'));
      
      // 禁用保存按钮
      document.querySelector('button[type="submit"]').disabled = true;
    }
  } catch (error) {
    console.error('加载名片夹失败:', error);
    
    // 显示更详细的错误信息
    const formContainer = document.querySelector('.container');
    if (formContainer) {
      const errorDiv = document.createElement('div');
      errorDiv.style.color = '#721c24';
      errorDiv.style.backgroundColor = '#f8d7da';
      errorDiv.style.padding = '10px';
      errorDiv.style.marginBottom = '15px';
      errorDiv.style.borderRadius = '4px';
      errorDiv.textContent = `加载名片夹失败: ${error.message}`;
      
      // 添加重试按钮
      const retryButton = document.createElement('button');
      retryButton.textContent = '重试';
      retryButton.style.marginLeft = '10px';
      retryButton.onclick = async () => {
        errorDiv.remove();
        await loadFolders();
      };
      
      // 添加返回主页按钮
      const homeButton = document.createElement('button');
      homeButton.textContent = '返回主页';
      homeButton.style.marginLeft = '10px';
      homeButton.onclick = () => {
        window.location.href = 'main.html';
      };
      
      errorDiv.appendChild(retryButton);
      errorDiv.appendChild(homeButton);
      
      // 在表单前插入错误提示
      if (document.getElementById('cardForm')) {
        formContainer.insertBefore(errorDiv, document.getElementById('cardForm'));
      } else {
        formContainer.appendChild(errorDiv);
      }
    } else {
      alert('加载名片夹数据失败，请刷新页面重试');
    }
  } finally {
    hideLoading();
  }
}

/**
 * 处理表单提交
 * @param {Event} e - 表单提交事件
 */
async function handleFormSubmit(e) {
  e.preventDefault();
  
  // 获取表单数据
  const folderId = document.getElementById('folder').value;
  
  if (!folderId) {
    alert('请选择一个名片夹');
    return;
  }
  
  const formData = {
    name: document.getElementById('name').value.trim(),
    title: document.getElementById('title').value.trim(),
    department: document.getElementById('department').value.trim(),
    company: document.getElementById('company').value.trim(),
    phone: document.getElementById('phone').value.trim(),
    email: document.getElementById('email').value.trim(),
    address: document.getElementById('address').value.trim(),
    zip: document.getElementById('zip').value.trim(),
    notes: document.getElementById('notes').value.trim()
  };
  
  // 表单验证
  if (!formData.name) {
    alert('姓名不能为空');
    return;
  }
  
  // 验证邮编长度，防止数据库错误
  if (formData.zip && formData.zip.length > 20) {
    alert('邮编长度不能超过20个字符');
    return;
  }
  
  try {
    // 显示加载中状态
    showLoading();
    
    // 检查JWT令牌是否存在
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('认证失败：未找到令牌');
    }
    
    // 禁用表单元素，防止重复提交
    toggleFormElements(true);
    
    // 提交数据 - API会自动添加令牌到请求头
    const response = await window.api.cards.create(folderId, formData);
    
    if (response.success) {
      alert('名片添加成功');
      // 返回主页面
      window.location.href = 'main.html';
    } else {
      throw new Error(response.message || '添加名片失败');
    }
  } catch (error) {
    console.error('添加名片错误:', error);
    alert(`添加名片失败: ${error.message || '未知错误'}`);
    // 重新启用表单元素
    toggleFormElements(false);
    hideLoading();
  }
}

/**
 * 切换表单元素的禁用状态
 * @param {boolean} disabled - 是否禁用
 */
function toggleFormElements(disabled) {
  // 获取所有表单元素
  const formElements = document.querySelectorAll('#cardForm input, #cardForm textarea, #cardForm select, #cardForm button');
  
  // 设置禁用状态
  formElements.forEach(element => {
    element.disabled = disabled;
  });
  
  // 如果禁用，显示加载提示
  const submitButton = document.querySelector('button[type="submit"]');
  if (disabled) {
    submitButton.textContent = '保存中...';
  } else {
    submitButton.textContent = '保存';
  }
}

/**
 * 显示加载覆盖层
 */
function showLoading() {
  document.getElementById('loadingOverlay').style.display = 'flex';
}

/**
 * 隐藏加载覆盖层
 */
function hideLoading() {
  document.getElementById('loadingOverlay').style.display = 'none';
} 